package alg;
import java.util.List;


import data.UserRatingList;

import exception.DataManagerException;

public class SimilarityPearson extends SimilarityAlgorithm {

	@Override
	public double eval(int UserId1, int UserId2, DataManager manager)
			throws DataManagerException {
		UserRatingList ratingsu1 = manager.getRatings(UserId1);
		UserRatingList ratingsu2 = manager.getRatings(UserId2);
		double similarity = 0;
		double mean_ratingu1 = ratingsu1.getMeanRating();
		double mean_ratingu2 = ratingsu2.getMeanRating();
		double den, num_sum1, num_sum2;
		int i = 0;
		List<Integer> commonratings = ratingsu1.intersect(ratingsu2);

		den = 0;
		num_sum1 = 0;
		num_sum2 = 0;
		this.common_ratings_size = commonratings.size();
		if (num_sum1 != 0 && num_sum2 != 2) {
			while (i < common_ratings_size) {
				int UserId = commonratings.get(i);
				double rating1 = ratingsu1.getRating(UserId) - mean_ratingu1;
				double rating2 = ratingsu2.getRating(UserId) - mean_ratingu2;
				den += rating1 * rating2;
				num_sum1 += rating1 * rating1;
				num_sum2 += rating2 * rating2;
				i++;
			}
			// System.out.println(intersection.size());
			similarity = den / Math.sqrt(num_sum1 * num_sum2);
		}
		return similarity;
	}

	

}
